package com.cspm.gen.controller;

import com.alibaba.fastjson.JSON;
import com.cspm.common.core.Result;
import com.cspm.gen.enums.DriverCLassEnum;
import com.cspm.gen.service.SystemGeneratorService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 代码生成器
 *
 * @author CHENQUAN
 * @date 2017年4月15日
 */
@Controller
@RequestMapping("/generator")
@Api(value = "/generator", description = "代码生成器")
public class SystemGeneratorController {
    @Resource
    private SystemGeneratorService systemGeneratorService;

    /**
     * 连接数据库
     *
     * @param dbType   数据库类型
     * @param server   服务器地址
     * @param port     端口号
     * @param database 数据库名
     * @param username 登录名
     * @param password 密码
     * @return 连接是否成功
     */
    @ApiOperation(value = "连接数据库", notes = "连接数据库")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dbType", value = "数据库类型", paramType = "query", required = true, dataType = "string"),
            @ApiImplicitParam(name = "server", value = "服务器地址", paramType = "query", required = true, dataType = "string"),
            @ApiImplicitParam(name = "port", value = "端口号", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = "database", value = "数据库名", paramType = "query", required = true, dataType = "string"),
            @ApiImplicitParam(name = "username", value = "登录名", paramType = "query", required = true, dataType = "string"),
            @ApiImplicitParam(name = "password", value = "密码", paramType = "query", required = true, dataType = "string"),
    })
    @ResponseBody
    @RequestMapping(value = "/connectDatabase", method = RequestMethod.POST)
    public Result connectDatabase(@RequestParam(value = "dbType", defaultValue = "mysql") String dbType,
                                  String server, Integer port, String database, String username, String password) {
        Result result;
        DriverCLassEnum driverCLassEnum = DriverCLassEnum.getDBType(dbType);
        if (driverCLassEnum == null) {
            result = new Result(100, "数据库类型无效！");
        } else {
            //连接数据库
            String connect = systemGeneratorService.connectDatabase(driverCLassEnum, server, port, database, username, password);
            result = new Result(1, connect);
        }
        return result;
    }

    /**
     * 数据库表列表模糊查询
     */
    @ApiOperation(value = "数据库表列表模糊查询", notes = "数据库表列表模糊查询")
    @ApiImplicitParams({@ApiImplicitParam(name = "tableName", value = "表名", paramType = "query", required = false, dataType = "string"),
            @ApiImplicitParam(name = "page", value = "页码", paramType = "query", required = false, dataType = "int"),
            @ApiImplicitParam(name = "rows", value = "行数", paramType = "query", required = false, dataType = "int")})
    @ResponseBody
    @RequestMapping(value = "/queryList", method = RequestMethod.POST)
    public Result queryList(String tableName, @RequestParam(value = "page", defaultValue = "1") Integer page,
                            @RequestParam(value = "rows", defaultValue = "10") Integer rows) {
        //查询列表数据
        PageInfo<Map<String, Object>> pageInfo = systemGeneratorService.queryList(tableName, page, rows);
        return new Result(1, pageInfo);
    }

    /**
     * 生成代码
     */
    @ApiOperation(value = "生成代码", notes = "生成代码")
    @ApiImplicitParams({@ApiImplicitParam(name = "codePackage", value = "包名。如：com.cspm.ap.user", defaultValue = "com.cspm", paramType = "query", required = true, dataType = "string"),
            @ApiImplicitParam(name = "author", value = "创建人。用于注解", paramType = "query", required = true, dataType = "string"),
            @ApiImplicitParam(name = "table", value = "表名", paramType = "query", required = true, dataType = "string")})
    @RequestMapping(value = "/code", method = RequestMethod.GET)
    public void code(String codePackage, String author, String table, HttpServletResponse response) throws IOException {
        String[] tableNames = new String[1];
        tableNames[0] = table;
        byte[] data = new byte[0];
        try {
            data = systemGeneratorService.generatorCode(codePackage, author, tableNames);
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=code-" + table + ".zip");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

    /**
     * 生成代码
     */
    @ApiOperation(value = "生成代码，批量", notes = "生成代码，批量")
    @ApiImplicitParams({@ApiImplicitParam(name = "codePackage", value = "包名。如：com.cspm", defaultValue = "com.cspm", paramType = "query", required = true, dataType = "string"),
            @ApiImplicitParam(name = "author", value = "创建人。用于注解", paramType = "query", required = true, dataType = "string"),
            @ApiImplicitParam(name = "tables", value = "表名JSONArray", defaultValue = "[\"a\",\"b\",\"c\"]", paramType = "query", required = true, dataType = "string")})
    @RequestMapping(value = "/codes", method = RequestMethod.GET)
    public void codes(String codePackage, String author, String tables, HttpServletResponse response) throws Exception {
        String[] tableNames = new String[]{};
        tableNames = JSON.parseArray(tables).toArray(tableNames);
        byte[] data = systemGeneratorService.generatorCode(codePackage, author, tableNames);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=code-" + new Date().toLocaleString() + ".zip");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

    /**
     * 生成代码，全部生成
     */
    @ApiOperation(value = "生成代码，全部表", notes = "生成代码，全部表")
    @ApiImplicitParams({@ApiImplicitParam(name = "codePackage", value = "包名。如：com.cspm", defaultValue = "com.cspm", paramType = "query", required = true, dataType = "string"),
            @ApiImplicitParam(name = "author", value = "创建人。用于注解", paramType = "query", required = true, dataType = "string")})
    @RequestMapping(value = "/codeAll", method = RequestMethod.GET)
    public void codeAll(String codePackage, String author, HttpServletResponse response) throws Exception {
        byte[] data = systemGeneratorService.generatorCodeAll(codePackage, author);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code-" + new Date().toLocaleString() + ".zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}